package com.demo.controller;

import com.demo.util.DES;
import com.demo.util.RandomUtil;
import com.demo.util.VerifyUtil;
import com.demo.vo.PasswordParam;
import com.demo.vo.Result;
import com.demo.vo.User;
import com.demo.vo.UserParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;


@Controller
public class DemoController {

    private static String TOKEN = "token";

    private static String SALT = "salt";

    private static String VERIFY_CODE = "verify_code";

    @GetMapping("login")
    public String loginPage(HttpServletRequest request, Model model) {

        String token = null;
        String salt = null;

        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(10);//默认10秒

        //判断session中是否存在
        token = session.getAttribute(TOKEN)==null?RandomUtil.get(8):session.getAttribute(TOKEN).toString();
        salt = session.getAttribute(SALT)==null?RandomUtil.get(5):session.getAttribute(SALT).toString();

        System.out.println(String.format("token:%s , salt:%s", token, salt));

        session.setAttribute(TOKEN, token);
        session.setAttribute(SALT, salt);

        model.addAttribute("token", token);
        model.addAttribute("salt", salt);

        return "login";
    }

    @PostMapping("login")
    @ResponseBody
    public Result login(HttpServletRequest request, UserParam userParam) {

        HttpSession session = request.getSession();
        String token = session.getAttribute(TOKEN) == null ? null : session.getAttribute(TOKEN).toString();
        String salt = session.getAttribute(SALT) == null ? null : session.getAttribute(SALT).toString();

        //验证码
        String code = session.getAttribute(VERIFY_CODE) == null ? null : session.getAttribute(VERIFY_CODE).toString();

        if (token == null || salt == null || code == null) {
            System.out.println("session 过期");
            return Result.buildError();
        }

        System.out.println(String.format("session code:%s,request code:%s", code, userParam.getCode()));

        if(code.equalsIgnoreCase(userParam.getCode())){
            System.out.println("验证通过");
        }else{
            System.out.println("验证码错误");
            return Result.buildError();
        }

        System.out.println(String.format("username:%s ,password:%s", userParam.getUsername(), userParam.getPassword()));

        String username = null;
        String password = null;
        try {
            username = URLDecoder.decode(userParam.getUsername(), "utf-8");
            password = URLDecoder.decode(userParam.getPassword(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        /**
         * 加密：拼接字符串（明文+salt），然后进行DES加密
         * 解密：DES解密后截取字符串（去掉salt）
         */
        System.out.println("---------------开始解密-------------------");
        username = DES.decrypt(username, token);
        password = DES.decrypt(password, token);
        System.out.println(String.format("username:%s", username.substring(0, username.indexOf(salt))));
        System.out.println(String.format("password:%s", password.substring(0, password.indexOf(salt))));

        return Result.buildSuccess();
    }

    @GetMapping("verify")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = VerifyUtil.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = request.getSession();
        session.setAttribute(VERIFY_CODE, codeMap.get("code").toString());

        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);

        response.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = response.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("user")
    public String userPage(Model model) {
        model.addAttribute("user", getTestData());
        return "user";
    }

    private User getTestData() {
        User user = new User();
        user.setId(1L);
        user.setLoginid("test");
        user.setUsername("用户名");
        user.setMobile("13624563385");
        user.setEmail("1223234@qq.com");
        user.setWeixinid("weixin");
        return user;
    }

    @PostMapping("saveUser")
    @ResponseBody
    public Result updateUser(User userParam) {

        return Result.buildSuccess();
    }

    @PostMapping("savePassword")
    @ResponseBody
    public Result savePassword(PasswordParam passwordParam) {

        System.out.println(String.format("old password:%s,new password:%s", passwordParam.getOld_pssword(), passwordParam.getNew_pssword()));

        return Result.buildSuccess();
    }
}
